package com.mobile.util;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.sql.*;
import java.util.*;
import java.util.stream.Collectors;

public class CodeGenerator {
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/mobile_dev?useSSL=false&serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PASSWORD = "sdbs";

    // 需要排除的字段（审计字段）
    private static final Set<String> EXCLUDED_FIELDS = new HashSet<>(Arrays.asList(
            "CREATE_USER", "CREATE_DATETIME", "UPDATE_USER", "UPDATE_DATETIME"
    ));

    // 需要排除的字段-更新
    private static final Set<String> EXCLUDED_FIELDS_UPDATE = new HashSet<>(Arrays.asList(
            "CREATE_USER", "CREATE_DATETIME"
    ));
    // 包路径配置
    private static final Map<String, String> PACKAGE_PATHS = new HashMap<String, String>() {{
//        put("entity", "xiajin-hrss-service/src/main/java/com/mobile/service/lz/");
//        put("dto", "xiajin-hrss-service/src/main/java/com/mobile/service/lz/");
//        put("service", "xiajin-hrss-service/src/main/java/com/mobile/service/lz/");
//        put("serviceImpl", "xiajin-hrss-service/src/main/java/com/mobile/service/lz/");
//        put("controller", "xiajin-hrss-service/src/main/java/com/mobile/service/lz/");
//        put("mapper", "xiajin-hrss-service/src/main/java/com/mobile/service/lz/");
//        put("converter", "xiajin-hrss-service/src/main/java/com/mobile/service/lz/");
        put("entity", "xiajin-hrss-service/src/main/java/com/mobile/service/entity/");
        put("dto", "xiajin-hrss-service/src/main/java/com/mobile/service/dto/");
        put("service", "xiajin-hrss-service/src/main/java/com/mobile/service/inter/");
        put("serviceImpl", "xiajin-hrss-service/src/main/java/com/mobile/service/impl/");
        put("controller", "xiajin-hrss-web/src/main/java/com/mobile/web/");
        put("mapper", "xiajin-hrss-service/src/main/resources/mapper/mysql/");
        put("converter", "xiajin-hrss-service/src/main/java/com/mobile/service/convert/");
        put("mybatis", "xiajin-hrss-service/src/main/resources/mybatis/");
    }};

    // 基础输出目录
    private static final String BASE_OUTPUT_PATH = ""; // 使用项目极目录

    public static void main(String[] args) {
        String tableName = "b_work_order"; // 要生成的表名
        String tableComment = "工单表"; // 表注释

        try {
            // 1. 加载驱动
            Class.forName(DRIVER);

            // 2. 获取数据库连接
            try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
                // 3. 获取表元数据
                List<ColumnMeta> columns = getTableColumns(conn, tableName);

                // 4. 生成所有代码文件
                generateAllCode(tableName, tableComment, columns);

                System.out.println("代码生成完成！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取表字段元数据
     */
    private static List<ColumnMeta> getTableColumns(Connection conn, String tableName) throws SQLException {
        List<ColumnMeta> columns = new ArrayList<>();
        DatabaseMetaData metaData = conn.getMetaData();

        try (ResultSet rs = metaData.getColumns(null, null, tableName, null)) {
            while (rs.next()) {
                String columnName = rs.getString("COLUMN_NAME");
                String typeName = rs.getString("TYPE_NAME");
                String remarks = rs.getString("REMARKS");
                int dataType = rs.getInt("DATA_TYPE");

                // 判断是否为主键
                boolean isPrimaryKey = false;
                try (ResultSet pkRs = metaData.getPrimaryKeys(null, null, tableName)) {
                    while (pkRs.next()) {
                        if (columnName.equals(pkRs.getString("COLUMN_NAME"))) {
                            isPrimaryKey = true;
                            break;
                        }
                    }
                }

                columns.add(new ColumnMeta(
                        columnName,
                        sqlTypeToJavaType(dataType, typeName),
                        remarks,
                        isPrimaryKey
                ));
            }
        }

        return columns;
    }

    /**
     * SQL类型转Java类型
     */
    private static String sqlTypeToJavaType(int sqlType, String typeName) {
        switch (sqlType) {
            case Types.INTEGER:
            case Types.SMALLINT:
            case Types.TINYINT:
                return "Integer";
            case Types.BIGINT:
                return "Long";
            case Types.VARCHAR:
            case Types.CHAR:
            case Types.LONGVARCHAR:
            case Types.NVARCHAR:
            case Types.NCHAR:
                return "String";
            case Types.DATE:
            case Types.TIME:
            case Types.TIMESTAMP:
                return "Date";
            case Types.BIT:
            case Types.BOOLEAN:
                return "Boolean";
            case Types.DECIMAL:
            case Types.NUMERIC:
                return "BigDecimal";
            case Types.DOUBLE:
            case Types.FLOAT:
                return "Double";
            default:
                return "Object"; // 未知类型
        }
    }

    /**
     * 生成所有代码文件
     */
    private static void generateAllCode(String tableName, String tableComment, List<ColumnMeta> columns) {
        // 基础命名转换
        String className = toCamelCase(tableName.replace("b_", ""), true);
        String lowerClassName = className.substring(0, 1).toLowerCase() + className.substring(1);
        String entityName = tableComment.replace("表", "");

        // 过滤掉排除字段
        List<ColumnMeta> filteredColumns = columns.stream()
                .filter(col -> !EXCLUDED_FIELDS.contains(col.name))
                .collect(Collectors.toList());

        // 获取主键字段
        ColumnMeta primaryKeyColumn = columns.stream()
                .filter(ColumnMeta::isPrimaryKey)
                .findFirst()
                .orElseThrow(() -> new RuntimeException("未找到主键字段"));

        // 1. 生成实体类
        generateEntityFile(tableName, tableComment, className, columns);

        // 2. 生成DTO
        generateDtoFile(tableName, tableComment, className, filteredColumns);

        // 3. 生成QueryDTO
        generateQueryDtoFile(tableName, tableComment, className, columns);

        // 4. 生成Service接口
        generateServiceFile(tableName, tableComment, className, entityName, primaryKeyColumn);

        // 5. 生成ServiceImpl
        generateServiceImplFile(tableName, tableComment, className, lowerClassName,
                columns, primaryKeyColumn);


        // 6. 生成Mapper XML
        generateMapperXmlFile(tableName, tableComment, className, lowerClassName,
                entityName, columns, primaryKeyColumn);

        // 7. 生成Controller
        generateControllerFile(tableName, tableComment, className, lowerClassName,
                entityName, primaryKeyColumn);
        // 8. 生成Converter
        generateConverterFile(className);

        // 9. 更新mybatis-config.xml别名配置
        generateMybatisConfigAliases(className);
    }

    /**
     * 生成实体类文件
     */
    private static void generateEntityFile(String tableName, String tableComment,
                                           String className, List<ColumnMeta> columns) {
        boolean hasDate = columns.stream().anyMatch(col -> "Date".equals(col.javaType));

        StringBuilder sb = new StringBuilder();
        sb.append("package com.mobile.service.entity;\n");
        sb.append("import com.baomidou.mybatisplus.annotation.*;\n");
        sb.append("import lombok.Data;\n");
        sb.append("import lombok.experimental.Accessors;\n\n");
        if (hasDate) {
            sb.append("import java.util.Date;\n\n");
        }
        sb.append("/**\n");
        sb.append(" * ").append(tableComment).append("\n");
        sb.append(" */\n");
        sb.append("@Data\n");
        sb.append("@TableName(\"").append(tableName).append("\")\n");
        sb.append("@Accessors(chain = true, fluent = true)\n");
        sb.append("public class ").append(className).append(" {\n");

        // 使用Set确保字段唯一性
        Set<String> addedFields = new HashSet<>();
        for (ColumnMeta col : columns) {
            String fieldName = toCamelCase(col.name, false);

            // 确保字段只添加一次
            if (addedFields.contains(fieldName)) {
                continue;
            }
            addedFields.add(fieldName);

            if (col.isPrimaryKey) {
                sb.append("    @TableId(type = IdType.AUTO)\n");
            }
            sb.append("    private ").append(col.javaType).append(" ")
                    .append(fieldName).append(";\n");
        }

        sb.append("}\n");

        String filePath = PACKAGE_PATHS.get("entity") + className + ".java";
        writeToFile(filePath, sb.toString());
    }

    /**
     * 生成DTO文件
     */
    private static void generateDtoFile(String tableName, String tableComment,
                                        String className, List<ColumnMeta> columns) {
        boolean hasDate = columns.stream().anyMatch(col -> "Date".equals(col.javaType));

        StringBuilder sb = new StringBuilder();
        sb.append("package com.mobile.service.dto;\n");
        sb.append("import com.mobile.service.dto.base.BaseDTO;\n");
        sb.append("import io.swagger.v3.oas.annotations.media.Schema;\n");
        sb.append("import lombok.Data;\n");
        sb.append("import lombok.EqualsAndHashCode;\n\n");
        if (hasDate) {
            sb.append("import java.util.Date;\n\n");
        }
        sb.append("/**\n");
        sb.append(" * ").append(tableComment).append("\n");
        sb.append(" */\n");
        sb.append("@EqualsAndHashCode(callSuper = true)\n");
        sb.append("@Data\n");
        sb.append("public class ").append(className).append("DTO extends BaseDTO {\n");

        // 使用Set确保字段唯一性
        Set<String> addedFields = new HashSet<>();
        for (ColumnMeta col : columns) {
            String fieldName = toCamelCase(col.name, false);

            // 确保字段只添加一次
            if (addedFields.contains(fieldName)) {
                continue;
            }
            // 排除审计字段
            if (EXCLUDED_FIELDS.contains(col.name)) {
                continue;
            }
            addedFields.add(fieldName);

            sb.append("    @Schema(description = \"").append(col.comment).append("\"");
            if (col.isPrimaryKey) {
                sb.append(", accessMode = Schema.AccessMode.READ_ONLY");
            } else {
                sb.append(", requiredMode = Schema.RequiredMode.REQUIRED");
            }
            sb.append(")\n");
            sb.append("    private ").append(col.javaType).append(" ")
                    .append(fieldName).append(";\n\n");
        }

        sb.append("}\n");

        String filePath = PACKAGE_PATHS.get("dto") + className + "DTO.java";
        writeToFile(filePath, sb.toString());
    }

    /**
     * 生成QueryDTO文件
     */
    private static void generateQueryDtoFile(String tableName, String tableComment,
                                             String className, List<ColumnMeta> columns) {
        boolean hasDate = columns.stream().anyMatch(col -> "Date".equals(col.javaType));

        StringBuilder sb = new StringBuilder();
        sb.append("package com.mobile.service.dto;\n");
        sb.append("import com.mobile.service.dto.base.PageDTO;\n");
        sb.append("import io.swagger.v3.oas.annotations.media.Schema;\n");
        sb.append("import lombok.Data;\n");
        sb.append("import lombok.EqualsAndHashCode;\n\n");
        if (hasDate) {
            sb.append("import java.util.Date;\n\n");
        }
        sb.append("/**\n");
        sb.append(" * ").append(tableComment).append("\n");
        sb.append(" */\n");
        sb.append("@EqualsAndHashCode(callSuper = true)\n");
        sb.append("@Data\n");
        sb.append("public class ").append(className).append("QueryDTO extends PageDTO {\n");

        // 使用Set确保字段唯一性
        Set<String> addedFields = new HashSet<>();
        for (ColumnMeta col : columns) {
            // 排除审计字段
            if (EXCLUDED_FIELDS.contains(col.name)) {
                continue;
            }

            if (!col.name.toLowerCase().contains("name") &&
                    !col.name.toLowerCase().contains("code")) {
                continue;
            }

            String fieldName = toCamelCase(col.name, false);

            // 确保字段只添加一次
            if (addedFields.contains(fieldName)) {
                continue;
            }
            addedFields.add(fieldName);

            sb.append("    @Schema(description = \"").append(col.comment).append("\")\n");
            sb.append("    private ").append(col.javaType).append(" ")
                    .append(fieldName).append(";\n\n");
        }

        sb.append("}\n");

        String filePath = PACKAGE_PATHS.get("dto") + className + "QueryDTO.java";
        writeToFile(filePath, sb.toString());
    }

    /**
     * 生成Service接口文件
     */
    private static void generateServiceFile(String tableName, String tableComment,
                                            String className, String entityName,
                                            ColumnMeta primaryKeyColumn) {
        String pkType = primaryKeyColumn.javaType;

        StringBuilder sb = new StringBuilder();
        sb.append("package com.mobile.service.inter;\n\n");
        sb.append("import com.mobile.service.dto.").append(className).append("DTO;\n");
        sb.append("import com.mobile.service.dto.").append(className).append("QueryDTO;\n");
        sb.append("import com.mobile.util.PageResult;\n\n");
        sb.append("import java.util.List;\n");
        sb.append("import java.util.Map;\n\n");
        sb.append("/**\n");
        sb.append(" * ").append(tableComment).append("Service接口\n");
        sb.append(" */\n");
        sb.append("public interface ").append(className).append("Service {\n\n");
        sb.append("    /**\n");
        sb.append("     * 新增").append(entityName).append("\n");
        sb.append("     */\n");
        sb.append("    Map<String, Object> add").append(className).append("(")
                .append(className).append("DTO dto) throws Exception;\n\n");
        sb.append("    /**\n");
        sb.append("     * 分页获取").append(entityName).append("列表\n");
        sb.append("     */\n");
        sb.append("    PageResult<").append(className).append("DTO> get")
                .append(className).append("ListPage(").append(className)
                .append("QueryDTO queryDTO) throws Exception;\n\n");
        sb.append("    /**\n");
        sb.append("     * 根据主键获取").append(entityName).append("信息\n");
        sb.append("     */\n");
        sb.append("    ").append(className).append("DTO get")
                .append(className).append("ById(").append(pkType).append(" id) throws Exception;\n\n");
        sb.append("    /**\n");
        sb.append("     * 修改").append(entityName).append("信息\n");
        sb.append("     */\n");
        sb.append("    Map<String, Object> update")
                .append(className).append("(").append(className)
                .append("DTO dto) throws Exception;\n\n");
        sb.append("    /**\n");
        sb.append("     * 根据主键删除").append(entityName).append("\n");
        sb.append("     */\n");
        sb.append("    Map<String, Object> remove")
                .append(className).append("(").append(pkType).append(" id) throws Exception;\n\n");
        sb.append("    /**\n");
        sb.append("     * 条件查询").append(entityName).append("列表\n");
        sb.append("     */\n");
        sb.append("    List<").append(className).append("DTO> get")
                .append(className).append("List(").append(className)
                .append("DTO dto) throws Exception;\n");
        sb.append("}\n");

        String filePath = PACKAGE_PATHS.get("service") + className + "Service.java";
        writeToFile(filePath, sb.toString());
    }

    /**
     * 生成ServiceImpl文件
     */
    private static void generateServiceImplFile(String tableName, String tableComment,
                                                String className, String lowerClassName,
                                                List<ColumnMeta> columns,
                                                ColumnMeta primaryKeyColumn) {
        // 动态主键字段处理
        String pkFieldName = toCamelCase(primaryKeyColumn.name, false);
        String pkGetter = "get" + toCamelCase(primaryKeyColumn.name, true);
        String pkType = primaryKeyColumn.javaType;

        // 查找需要查重的字段（包含name或code的字段）
        Optional<ColumnMeta> duplicateCheckField = columns.stream()
                .filter(col -> col.name.toLowerCase().contains("name") ||
                        col.name.toLowerCase().contains("code"))
                .findFirst();

        StringBuilder sb = new StringBuilder();
        sb.append("package com.mobile.service.impl;\n\n");
        sb.append("import com.github.pagehelper.PageInfo;\n");
        sb.append("import com.mobile.service.convert.").append(className).append("Converter;\n");
        sb.append("import com.mobile.service.dao.DaoSupport;\n");
        sb.append("import com.mobile.service.dto.").append(className).append("DTO;\n");
        sb.append("import com.mobile.service.dto.").append(className).append("QueryDTO;\n");
        sb.append("import com.mobile.service.entity.").append(className).append(";\n");
        sb.append("import com.mobile.service.inter.").append(className).append("Service;\n");
        sb.append("import com.mobile.service.util.PageUtils;\n");
        sb.append("import com.mobile.util.*;\n");
        sb.append("import org.springframework.beans.factory.annotation.Autowired;\n");
        sb.append("import org.springframework.stereotype.Service;\n");
        sb.append("import org.springframework.transaction.annotation.Transactional;\n\n");
        sb.append("import javax.annotation.Resource;\n");
        sb.append("import java.util.HashMap;\n");
        sb.append("import java.util.List;\n");
        sb.append("import java.util.Map;\n");
        sb.append("import java.util.Objects;\n\n");
        sb.append("/**\n");
        sb.append(" * ").append(tableComment).append("service实现类\n");
        sb.append(" */\n");
        sb.append("@Service(\"").append(lowerClassName).append("Service\")\n");
        sb.append("@Transactional\n");
        sb.append("public class ").append(className).append("ServiceImpl implements ")
                .append(className).append("Service {\n");
        sb.append("    @Resource(name = \"daoSupport\")\n");
        sb.append("    private DaoSupport dao;\n");
        sb.append("    @Autowired\n");
        sb.append("    private ").append(className).append("Converter ")
                .append(lowerClassName).append("Converter;\n\n");

        // 新增方法实现
        sb.append("    @Override\n");
        sb.append("    public Map<String, Object> add").append(className)
                .append("(").append(className).append("DTO dto) throws Exception {\n");
        sb.append("        Map<String, Object> map = new HashMap<>();\n");

        if (duplicateCheckField.isPresent()) {
            ColumnMeta field = duplicateCheckField.get();
            String fieldName = toCamelCase(field.name, false);
            String fieldValue = "dto.get" + toCamelCase(field.name, true) + "()";

            sb.append("        ").append(className).append("DTO pd = (")
                    .append(className).append("DTO) dao.findForObject(\"")
                    .append(className).append("Mapper.get").append(className)
                    .append("By").append(toCamelCase(field.name, true))
                    .append("\", ").append(fieldValue).append(");\n");
            sb.append("        if (null == pd) {\n");
            sb.append("            dao.save(\"").append(className).append("Mapper.insert")
                    .append(className).append("\", ").append(lowerClassName)
                    .append("Converter.toEntity(dto));\n");
            sb.append("            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);\n");
            sb.append("            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage(\"I0011\"));\n");
            sb.append("        } else {\n");
            sb.append("            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);\n");
            sb.append("            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage(\"E0004\", \"该")
                    .append(field.comment).append("\"));\n");
            sb.append("        }\n");
        } else {
            sb.append("        dao.save(\"").append(className).append("Mapper.insert")
                    .append(className).append("\", ").append(lowerClassName)
                    .append("Converter.toEntity(dto));\n");
            sb.append("        map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);\n");
            sb.append("        map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage(\"I0011\"));\n");
        }

        sb.append("        return map;\n");
        sb.append("    }\n\n");

        // 分页查询方法实现
        sb.append("    @SuppressWarnings(\"unchecked\")\n");
        sb.append("    @Override\n");
        sb.append("    public PageResult<").append(className).append("DTO> get")
                .append(className).append("ListPage(").append(className)
                .append("QueryDTO queryDTO) throws Exception {\n");
        sb.append("        PageUtils.startPage(queryDTO);\n");
        sb.append("        List<").append(className).append("DTO> list = (List<")
                .append(className).append("DTO>) dao.findForList(\"")
                .append(className).append("Mapper.").append(lowerClassName)
                .append("listPage\", queryDTO);\n");
        sb.append("        return new PageResult<").append(className).append("DTO>(list);\n");
        sb.append("    }\n\n");

        // 根据ID查询方法实现
        sb.append("    @Override\n");
        sb.append("    public ").append(className).append("DTO get")
                .append(className).append("ById(").append(pkType).append(" id) throws Exception {\n");
        sb.append("        return (").append(className).append("DTO) dao.findForObject(\"")
                .append(className).append("Mapper.get").append(className).append("ById\", id);\n");
        sb.append("    }\n\n");

        // 更新方法实现
        sb.append("    @Override\n");
        sb.append("    public Map<String, Object> update")
                .append(className).append("(").append(className)
                .append("DTO dto) throws Exception {\n");
        sb.append("        Map<String, Object> map = new HashMap<>();\n");
        sb.append("        ").append(pkType).append(" pkValue = dto.").append(pkGetter).append("();\n");
        sb.append("        if (pkValue == null) {\n");
        sb.append("            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);\n");
        sb.append("            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage(\"E0001\"));\n");
        sb.append("            return map;\n");
        sb.append("        }\n\n");

        sb.append("        ").append(className).append("DTO data = this.get")
                .append(className).append("ById(pkValue);\n");
        sb.append("        if (Objects.isNull(data)) {\n");
        sb.append("            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);\n");
        sb.append("            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage(\"E0001\"));\n");
        sb.append("            return map;\n");
        sb.append("        }\n\n");

        if (duplicateCheckField.isPresent()) {
            ColumnMeta field = duplicateCheckField.get();
            String fieldName = toCamelCase(field.name, false);
            String fieldValue = "dto.get" + toCamelCase(field.name, true) + "()";

            sb.append("        ").append(className).append("DTO pd = (")
                    .append(className).append("DTO) dao.findForObject(\"")
                    .append(className).append("Mapper.get").append(className)
                    .append("By").append(toCamelCase(field.name, true))
                    .append("\", ").append(fieldValue).append(");\n");
            sb.append("        if (null == pd || pd.").append(pkGetter).append("().equals(pkValue)) {\n");
            sb.append("            dao.update(\"").append(className).append("Mapper.update")
                    .append(className).append("\", ").append(lowerClassName)
                    .append("Converter.toEntity(dto));\n");
            sb.append("            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);\n");
            sb.append("            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage(\"I0009\"));\n");
            sb.append("        } else {\n");
            sb.append("            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);\n");
            sb.append("            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage(\"E0004\", \"该")
                    .append(field.comment).append("\"));\n");
            sb.append("        }\n");
        } else {
            sb.append("        dao.update(\"").append(className).append("Mapper.update")
                    .append(className).append("\", ").append(lowerClassName)
                    .append("Converter.toEntity(dto));\n");
            sb.append("            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);\n");
            sb.append("            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage(\"I0009\"));\n");
        }

        sb.append("        return map;\n");
        sb.append("    }\n\n");

        // 删除方法实现
        sb.append("    @Override\n");
        sb.append("    public Map<String, Object> remove")
                .append(className).append("(").append(pkType).append(" id) throws Exception {\n");
        sb.append("        Map<String, Object> map = new HashMap<>();\n");
        sb.append("        dao.delete(\"").append(className).append("Mapper.delete")
                .append(className).append("\", id);\n");
        sb.append("        map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);\n");
        sb.append("        map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage(\"I0010\"));\n");
        sb.append("        return map;\n");
        sb.append("    }\n\n");

        // 新增条件查询方法实现
        sb.append("    @SuppressWarnings(\"unchecked\")\n");
        sb.append("    @Override\n");
        sb.append("    public List<").append(className).append("DTO> get")
                .append(className).append("List(").append(className)
                .append("DTO dto) throws Exception {\n");
        sb.append("        return (List<").append(className).append("DTO>) dao.findForList(\"")
                .append(className).append("Mapper.get").append(className)
                .append("List\", dto);\n");
        sb.append("    }\n");
        sb.append("}\n");

        String filePath = PACKAGE_PATHS.get("serviceImpl") + className + "ServiceImpl.java";
        writeToFile(filePath, sb.toString());
    }

    /**
     * 生成Mapper XML文件
     */
    private static void generateMapperXmlFile(String tableName, String tableComment,
                                              String className, String lowerClassName,
                                              String entityName, List<ColumnMeta> columns,
                                              ColumnMeta primaryKeyColumn) {
        // 动态识别查询字段（包含"name"或"code"的字段）
        Set<String> addedQueryFields = new HashSet<>();
        List<ColumnMeta> queryFields = new ArrayList<>();
        for (ColumnMeta col : columns) {
            if (col.name.toLowerCase().contains("name") ||
                    col.name.toLowerCase().contains("code")) {
                String fieldName = toCamelCase(col.name, false);
                if (!addedQueryFields.contains(fieldName)) {
                    addedQueryFields.add(fieldName);
                    queryFields.add(col);
                }
            }
        }

        // 主键字段信息
        String pkFieldName = toCamelCase(primaryKeyColumn.name, false);
        String pkColumnName = primaryKeyColumn.name;

        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        sb.append("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \n");
        sb.append("\"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n");
        sb.append("<mapper namespace=\"").append(className).append("Mapper\">\n\n");

        // 添加记录
        sb.append("    <!--添加").append(entityName).append("信息-->\n");
        sb.append("    <insert id=\"insert").append(className).append("\" parameterType=\"")
                .append(className).append("\">\n");
        sb.append("        INSERT INTO ").append(tableName).append(" (\n");

        // 插入列 - 确保字段唯一性
        Set<String> addedColumns = new HashSet<>();
        String insertColumns = columns.stream()
                .filter(col -> !col.isPrimaryKey)
                .filter(col -> addedColumns.add(col.name)) // 确保唯一
                .map(ColumnMeta::getName)
                .collect(Collectors.joining(",\n            "));
        sb.append("            ").append(insertColumns).append("\n");

        sb.append("        )\n");
        sb.append("        VALUES (\n");

        // 插入值 - 确保字段唯一性
        addedColumns.clear();
        String insertValues = columns.stream()
                .filter(col -> !col.isPrimaryKey)
                .filter(col -> addedColumns.add(col.name)) // 确保唯一
                .map(col -> "#{" + toCamelCase(col.name, false) + "}")
                .collect(Collectors.joining(",\n            "));
        sb.append("            ").append(insertValues).append("\n");

        sb.append("        )\n");
        sb.append("    </insert>\n\n");

        // 分页查询
        sb.append("    <!--分页获取").append(entityName).append("列表-->\n");
        sb.append("    <select id=\"").append(lowerClassName).append("listPage\" parameterType=\"")
                .append(className).append("QueryDTO\" \n");
        sb.append("        resultType=\"").append(className).append("DTO\">\n");
        sb.append("        SELECT\n");

        // 选择列 - 确保字段唯一性
        addedColumns.clear();
        String selectColumns = columns.stream()
                .filter(col -> addedColumns.add(col.name)) // 确保唯一
                .map(col -> "a." + col.name + " AS " + toCamelCase(col.name, false))
                .collect(Collectors.joining(",\n            "));
        sb.append("            ").append(selectColumns).append("\n");

        sb.append("        FROM\n");
        sb.append("            ").append(tableName).append(" a\n");
        sb.append("        <where>\n");

        // 动态生成查询条件
        for (ColumnMeta col : columns) {
            String field = toCamelCase(col.name, false);
            // 字符串字段需要同时检查非null和非空
            if ("String".equals(col.javaType)) {
                sb.append("            <if test=\"").append(field).append(" != null and ")
                        .append(field).append(" != ''\">\n");
            } else {
                sb.append("            <if test=\"").append(field).append(" != null\">\n");
            }

            sb.append("                AND a.").append(col.name);

            if (col.name.toLowerCase().contains("code")) {
                sb.append(" LIKE CONCAT(#{").append(field).append("}, '%')\n");
            } else {
                sb.append(" =#{").append(field).append("}\n");
            }
            sb.append("            </if>\n");
        }

        sb.append("        </where>\n");
        sb.append("        ORDER BY a.update_datetime desc\n");
        sb.append("    </select>\n\n");

        // 新增条件查询
        sb.append("    <!--条件查询").append(entityName).append("列表-->\n");
        sb.append("    <select id=\"get").append(className).append("List\" parameterType=\"")
                .append(className).append("DTO\" \n");
        sb.append("        resultType=\"").append(className).append("DTO\">\n");
        sb.append("        SELECT\n");
        sb.append("            ").append(selectColumns).append("\n");
        sb.append("        FROM\n");
        sb.append("            ").append(tableName).append(" a\n");
        sb.append("        <where>\n");

        // 动态生成查询条件
        for (ColumnMeta col : columns) {
            String field = toCamelCase(col.name, false);
            // 字符串字段需要同时检查非null和非空
            if ("String".equals(col.javaType)) {
                sb.append("            <if test=\"").append(field).append(" != null and ")
                        .append(field).append(" != ''\">\n");
            } else {
                sb.append("            <if test=\"").append(field).append(" != null\">\n");
            }

            sb.append("                AND a.").append(col.name);

            if (col.name.toLowerCase().contains("name")) {
                sb.append(" LIKE CONCAT(#{").append(field).append("}, '%')\n");
            } else {
                sb.append(" =#{").append(field).append("}\n");
            }
            sb.append("            </if>\n");
        }

        sb.append("        </where>\n");
        sb.append("        ORDER BY a.update_datetime desc\n");
        sb.append("    </select>\n\n");

        // 根据ID查询
        sb.append("    <!--根据主键获取").append(entityName).append("信息-->\n");
        sb.append("    <select id=\"get").append(className).append("ById\" parameterType=\"")
                .append(primaryKeyColumn.javaType).append("\" \n");
        sb.append("        resultType=\"").append(className).append("DTO\">\n");
        sb.append("        SELECT\n");

        // ID选择列 - 确保字段唯一性
        addedColumns.clear();
        String idSelectColumns = columns.stream()
                .filter(col -> !EXCLUDED_FIELDS.contains(col.name))
                .filter(col -> addedColumns.add(col.name)) // 确保唯一
                .map(col -> col.name + " AS " + toCamelCase(col.name, false))
                .collect(Collectors.joining(",\n            "));
        sb.append("            ").append(idSelectColumns).append("\n");

        sb.append("        FROM\n");
        sb.append("            ").append(tableName).append("\n");
        sb.append("        WHERE\n");
        sb.append("            ").append(pkColumnName).append(" = #{")
                .append(pkFieldName).append("}\n");
        sb.append("    </select>\n\n");

        // 更新记录 - 使用动态SQL更新非空字段
        sb.append("    <!--修改").append(entityName).append("信息-->\n");
        sb.append("    <update id=\"update").append(className).append("\" parameterType=\"")
                .append(className).append("\">\n");
        sb.append("        UPDATE ").append(tableName).append("\n");
        sb.append("        <set>\n");

        // 更新列 - 确保字段唯一性
        addedColumns.clear();
        for (ColumnMeta col : columns) {
            if (col.isPrimaryKey || EXCLUDED_FIELDS_UPDATE.contains(col.name)) {
                continue;
            }

            String fieldName = toCamelCase(col.name, false);

            if (addedColumns.contains(fieldName)) {
                continue;
            }
            addedColumns.add(fieldName);

            if ("UPDATE_DATETIME".equals(col.name)) {
                sb.append("                ").append(col.name).append(" = now(),\n");

            }else{
                // 字符串字段需要同时检查非null和非空
                if ("String".equals(col.javaType)) {
                    sb.append("            <if test=\"").append(fieldName).append(" != null and ")
                            .append(fieldName).append(" != ''\">\n");
                } else {
                    sb.append("            <if test=\"").append(fieldName).append(" != null\">\n");
                }

                sb.append("                ").append(col.name).append(" = #{").append(fieldName).append("},\n");
                sb.append("            </if>\n");
            }

        }

        sb.append("        </set>\n");
        sb.append("        WHERE ").append(pkColumnName).append(" = #{")
                .append(pkFieldName).append("}\n");
        sb.append("    </update>\n\n");

        // 删除记录
        sb.append("    <!--删除").append(entityName).append("信息-->\n");
        sb.append("    <delete id=\"delete").append(className).append("\" parameterType=\"")
                .append(primaryKeyColumn.javaType).append("\">\n");
        sb.append("        DELETE FROM ").append(tableName).append("\n");
        sb.append("        WHERE ").append(pkColumnName).append(" = #{")
                .append(pkFieldName).append("}\n");
        sb.append("    </delete>\n");

        sb.append("</mapper>\n");

        String filePath = PACKAGE_PATHS.get("mapper")  + className + "Mapper.xml";
        writeToFile(filePath, sb.toString());
    }

    /**
     * 生成Controller文件
     */
    private static void generateControllerFile(String tableName, String tableComment,
                                               String className, String lowerClassName,
                                               String entityName, ColumnMeta primaryKeyColumn) {
        String pkFieldName = toCamelCase(primaryKeyColumn.name, false);
        String pkType = primaryKeyColumn.javaType;

        StringBuilder sb = new StringBuilder();
        sb.append("package com.mobile.web.").append(lowerClassName).append(";\n\n");
        sb.append("import com.mobile.service.dto.").append(className).append("DTO;\n");
        sb.append("import com.mobile.service.dto.").append(className).append("QueryDTO;\n");
        sb.append("import com.mobile.service.inter.").append(className).append("Service;\n");
        sb.append("import com.mobile.util.*;\n");
        sb.append("import com.mobile.web.base.BaseController;\n");
        sb.append("import com.mobile.util.config.aop.AutoFill;\n");
        sb.append("import com.mobile.util.config.aop.OperateType;\n");
        sb.append("import io.swagger.v3.oas.annotations.Operation;\n");
        sb.append("import io.swagger.v3.oas.annotations.Parameter;\n");
        sb.append("import io.swagger.v3.oas.annotations.responses.ApiResponses;\n");
        sb.append("import io.swagger.v3.oas.annotations.tags.Tag;\n");
        sb.append("import org.apache.shiro.authz.annotation.RequiresPermissions;\n");
        sb.append("import org.springframework.beans.factory.annotation.Autowired;\n");
        sb.append("import org.springframework.validation.annotation.Validated;\n");
        sb.append("import org.springframework.web.bind.annotation.*;\n\n");
        sb.append("import javax.validation.Valid;\n");
        sb.append("import java.util.HashMap;\n");
        sb.append("import java.util.List;\n");
        sb.append("import java.util.Map;\n\n");
        sb.append("/**\n");
        sb.append(" * ").append(tableComment).append("API接口\n");
        sb.append(" */\n");
        sb.append("@RestController\n");
        sb.append("@RequestMapping(\"/").append(lowerClassName).append("\")\n");
        sb.append("@Tag(name = \"").append(entityName).append("管理接口\", description = \"包含")
                .append(entityName).append("的查询、新增、修改、删除等操作\")\n");
        sb.append("public class ").append(className).append("Controller extends BaseController {\n\n");
        sb.append("    @Autowired\n");
        sb.append("    private ").append(className).append("Service ").append(lowerClassName).append("Service;\n\n");

        // 添加方法
        sb.append("    @PostMapping(\"/add").append(className).append("\")\n");
        sb.append("    //@RequiresPermissions(\"").append(lowerClassName).append("mana:add:1\")\n");
        sb.append("    @Operation(summary = \"创建").append(entityName).append("\")\n");
        sb.append("    @AutoFill(OperateType.INSERT)\n");
        sb.append("    public Object add").append(className).append("(@Valid @RequestBody ").append(className)
                .append("DTO dto) {\n");
        sb.append("        Map<String, Object> map;\n");
        sb.append("        try {\n");
        sb.append("            map = ").append(lowerClassName).append("Service.add").append(className).append("(dto);\n");
        sb.append("        } catch (Exception e) {\n");
        sb.append("            map = new HashMap<>();\n");
        sb.append("            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);\n");
        sb.append("            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage(\"E0016\"));\n");
        sb.append("            logger.error(e.getMessage(), e);\n");
        sb.append("        }\n");
        sb.append("        return AppUtil.returnObject(map);\n");
        sb.append("    }\n\n");

        // 分页查询方法
        sb.append("    @GetMapping(value = \"/get").append(className).append("ListPage\")\n");
        sb.append("    //@RequiresPermissions(\"").append(lowerClassName).append("mana:read:1\")\n");
        sb.append("    @Operation(summary = \"分页查询").append(entityName).append("\")\n");
        sb.append("    public Object get").append(className).append("ListPage(@Validated ")
                .append(className).append("QueryDTO queryDTO) {\n");
        sb.append("        Map<String, Object> map = new HashMap<>();\n");
        sb.append("        try {\n");
        sb.append("            PageResult<").append(className).append("DTO> page = ")
                .append(lowerClassName).append("Service.get").append(className).append("ListPage(queryDTO);\n");
        sb.append("            map.put(\"page\", page);\n");
        sb.append("            map.put(\"data\", page.getPageDatas());\n");
        sb.append("            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);\n");
        sb.append("        } catch (Exception e) {\n");
        sb.append("            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);\n");
        sb.append("            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage(\"E0016\"));\n");
        sb.append("            logger.error(e.getMessage(), e);\n");
        sb.append("        }\n");
        sb.append("        return AppUtil.returnObject(map);\n");
        sb.append("    }\n\n");

        // 根据ID查询方法
        sb.append("    @GetMapping(value = \"/get").append(className).append("ById\")\n");
        sb.append("    //@RequiresPermissions(\"").append(lowerClassName).append("mana:edit:1\")\n");
        sb.append("    @Operation(summary = \"查询").append(entityName).append("详情\")\n");
        sb.append("    public Object get").append(className).append("ById(\n");
        sb.append("        @Parameter(description = \"").append(entityName).append("主键\", required = true) \n");
        sb.append("        @RequestParam(\"").append(pkFieldName).append("\") ").append(pkType).append(" id) {\n");
        sb.append("        Map<String, Object> map = new HashMap<>();\n");
        sb.append("        try {\n");
        sb.append("            ").append(className).append("DTO dto = ")
                .append(lowerClassName).append("Service.get").append(className).append("ById(id);\n");
        sb.append("            if (StringUtil.isEmpty(dto)) {\n");
        sb.append("                map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);\n");
        sb.append("                map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage(\"E0001\"));\n");
        sb.append("            } else {\n");
        sb.append("                map.put(\"data\", dto);\n");
        sb.append("                map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);\n");
        sb.append("            }\n");
        sb.append("        } catch (Exception e) {\n");
        sb.append("            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);\n");
        sb.append("            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage(\"E0016\"));\n");
        sb.append("            logger.error(e.getMessage(), e);\n");
        sb.append("        }\n");
        sb.append("        return AppUtil.returnObject(map);\n");
        sb.append("    }\n\n");

        // 更新方法
        sb.append("    @PostMapping(\"/update").append(className).append("\")\n");
        sb.append("    //@RequiresPermissions(\"").append(className).append("mana:edit:1\")\n");
        sb.append("    @Operation(summary = \"编辑").append(entityName).append("\")\n");
        sb.append("    @AutoFill(OperateType.UPDATE)\n");
        sb.append("    public Object update").append(className).append("(@Valid @RequestBody ")
                .append(className).append("DTO dto) {\n");
        sb.append("        Map<String, Object> map;\n");
        sb.append("        try {\n");
        sb.append("            map = ").append(lowerClassName).append("Service.update").append(className).append("(dto);\n");
        sb.append("        } catch (Exception e) {\n");
        sb.append("            map = new HashMap<>();\n");
        sb.append("            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);\n");
        sb.append("            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage(\"E0016\"));\n");
        sb.append("            logger.error(e.getMessage(), e);\n");
        sb.append("        }\n");
        sb.append("        return AppUtil.returnObject(map);\n");
        sb.append("    }\n\n");

        // 删除方法
        sb.append("    @GetMapping(\"/remove").append(className).append("\")\n");
        sb.append("    //@RequiresPermissions(\"").append(lowerClassName).append("mana:delete:1\")\n");
        sb.append("    public Object remove").append(className).append("(@RequestParam(\"")
                .append(pkFieldName).append("\") ").append(pkType).append(" id) {\n");
        sb.append("        Map<String, Object> map;\n");
        sb.append("        try {\n");
        sb.append("            map = ").append(lowerClassName).append("Service.remove").append(className).append("(id);\n");
        sb.append("        } catch (Exception e) {\n");
        sb.append("            map = new HashMap<>();\n");
        sb.append("            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);\n");
        sb.append("            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage(\"E0016\"));\n");
        sb.append("            logger.error(e.getMessage(), e);\n");
        sb.append("        }\n");
        sb.append("        return AppUtil.returnObject(map);\n");
        sb.append("    }\n\n");

        // 新增条件查询方法
        sb.append("    @GetMapping(\"/get").append(className).append("List\")\n");
        sb.append("    //@RequiresPermissions(\"").append(lowerClassName).append("mana:read:1\")\n");
        sb.append("    @Operation(summary = \"条件查询").append(entityName).append("列表\")\n");
        sb.append("    public Object get").append(className).append("List(@Valid @RequestBody ")
                .append(className).append("DTO dto) {\n");
        sb.append("        Map<String, Object> map = new HashMap<>();\n");
        sb.append("        try {\n");
        sb.append("            List<").append(className).append("DTO> list = ")
                .append(lowerClassName).append("Service.get").append(className).append("List(dto);\n");
        sb.append("            map.put(\"data\", list);\n");
        sb.append("            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);\n");
        sb.append("        } catch (Exception e) {\n");
        sb.append("            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_EXCEPTION);\n");
        sb.append("            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage(\"E0016\"));\n");
        sb.append("            logger.error(e.getMessage(), e);\n");
        sb.append("        }\n");
        sb.append("        return AppUtil.returnObject(map);\n");
        sb.append("    }\n");
        sb.append("}\n");

        String filePath = PACKAGE_PATHS.get("controller") + lowerClassName + "/" + className + "Controller.java";
        writeToFile(filePath, sb.toString());
    }

    private static void generateConverterFile(String className) {
        StringBuilder sb = new StringBuilder();
        sb.append("package com.mobile.service.convert;\n\n");
        sb.append("import com.mobile.service.dto.").append(className).append("DTO;\n");
        sb.append("import com.mobile.service.entity.").append(className).append(";\n");
        sb.append("import org.mapstruct.InheritInverseConfiguration;\n");
        sb.append("import org.mapstruct.Mapper;\n\n");
        sb.append("import java.util.List;\n");
        sb.append("import java.util.stream.Collectors;\n\n");
        sb.append("@Mapper(componentModel = \"spring\")\n");
        sb.append("public interface ").append(className).append("Converter {\n\n");
        sb.append("    // 基础映射\n");
        sb.append("    ").append(className).append(" toEntity(").append(className).append("DTO dto);\n\n");
        sb.append("    // 反向映射\n");
        sb.append("    @InheritInverseConfiguration\n");
        sb.append("    ").append(className).append("DTO toDto(").append(className).append(" entity);\n\n");
        sb.append("    // 集合映射\n");
        sb.append("    default List<").append(className).append("DTO> toDtoList(List<").append(className).append("> entities) {\n");
        sb.append("        return entities.stream()\n");
        sb.append("                .map(this::toDto)\n");
        sb.append("                .collect(Collectors.toList());\n");
        sb.append("    }\n");
        sb.append("}\n");

        String filePath = PACKAGE_PATHS.get("converter") + className + "Converter.java";
        writeToFile(filePath, sb.toString());
    }

    /**
     * 蛇形命名转驼峰命名
     */
    private static String toCamelCase(String input, boolean capitalizeFirst) {
        StringBuilder result = new StringBuilder();
        boolean capitalize = capitalizeFirst;

        for (String part : input.toLowerCase().split("_")) {
            if (part.isEmpty()) continue;
            if (capitalize) {
                result.append(part.substring(0, 1).toUpperCase());
            } else {
                result.append(part.substring(0, 1));
            }
            result.append(part.substring(1));
            capitalize = true;
        }
        return result.toString();
    }

    /**
     * 将内容写入文件（自动创建目录）
     */
    private static void writeToFile(String relativePath, String content) {
        try {
            // 确保目录存在
            File file = new File(BASE_OUTPUT_PATH + relativePath);
            File parentDir = file.getParentFile();
            if (!parentDir.exists()) {
                parentDir.mkdirs();
                System.out.println("创建目录: " + parentDir.getAbsolutePath());
            }

            // 写入文件
            try (java.io.FileWriter writer = new java.io.FileWriter(file)) {
                writer.write(content);
                System.out.println("生成文件: " + file.getAbsolutePath());
            }
        } catch (Exception e) {
            System.err.println("写入文件失败: " + relativePath + " - " + e.getMessage());
        }
    }

    /**
     * 字段元数据类
     */
    static class ColumnMeta {
        String name;
        String javaType;
        String comment;
        boolean isPrimaryKey;

        public ColumnMeta(String name, String javaType, String comment, boolean isPrimaryKey) {
            this.name = name;
            this.javaType = javaType;
            this.comment = comment;
            this.isPrimaryKey = isPrimaryKey;
        }

        public String getName() {
            return name;
        }

        public boolean isPrimaryKey() {
            return isPrimaryKey;
        }
    }

    /**
     * 向mybatis-config.xml添加别名配置
     */
    private static void generateMybatisConfigAliases(String className) {
        String configPath = PACKAGE_PATHS.get("mybatis")+"/mybatis-config.xml"; // 配置文件路径
        File configFile = new File(BASE_OUTPUT_PATH + configPath);

        if (!configFile.exists()) {
            System.err.println("mybatis-config.xml文件不存在: " + configFile.getAbsolutePath());
            return;
        }

        try {
            // 读取文件内容
            String content = new String(Files.readAllBytes(configFile.toPath()));
            String aliasTag = "</typeAliases>"; // 定位插入点

            // 检查是否已存在别名
            String dtoAlias = "<typeAlias type=\"com.mobile.service.dto." + className + "DTO\" alias=\"" + className + "DTO\"/>";
            String queryDtoAlias = "<typeAlias type=\"com.mobile.service.dto." + className + "QueryDTO\" alias=\"" + className + "QueryDTO\"/>";
            String entityAlias = "<typeAlias type=\"com.mobile.service.entity." + className + "\" alias=\"" + className + "\"/>";

            if (content.contains(dtoAlias) || content.contains(queryDtoAlias) || content.contains(entityAlias)) {
                System.out.println("别名已存在，跳过更新");
                return;
            }

            // 构建插入内容
            String insertContent = "\n\t\t" + dtoAlias +
                    "\n\t\t" + queryDtoAlias +
                    "\n\t\t" + entityAlias +
                    "\n\t";

            // 在</typeAliases>前插入新别名
            int insertIndex = content.indexOf(aliasTag);
            if (insertIndex == -1) {
                System.err.println("未找到</typeAliases>标签");
                return;
            }

            String newContent = content.substring(0, insertIndex) +
                    insertContent +
                    content.substring(insertIndex);

            // 写回文件
            Files.write(configFile.toPath(), newContent.getBytes());
            System.out.println("成功更新mybatis-config.xml");

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("更新mybatis-config.xml失败: " + e.getMessage());
        }
    }
}